<template>
  <el-dialog v-model="open" :show-close="false" @open="initOpen" @close="close" custom-class="lifeLineAssess-dialog"
    destroy-on-close width="1200px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" v-loading="formLoading"
      :scroll-to-error="true">
      <el-space direction="vertical">
        <div shadow="never" class="assess">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="评估记录编号：" prop="code">
                <el-input v-model="form.code" clearable :disabled="!!form.id"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评估记录名称：" prop="name">
                <el-input v-model="form.name" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="border-bottom">
            <el-col :span="24">
              <el-form-item label="评估记录描述：" prop="info">
                <el-input v-model="form.info" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" resize="none"
                  clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="border-bottom">
            <el-form-item :label="sourceData[type].name" style="display:block;width: 100%;" prop="dataSource">
              <el-col :span="24">
                <el-row justify="space-between">
                  <el-checkbox-group v-model="form.dataSource" @change="dataSourceChange">
                    <el-checkbox v-for="item in sourceData[type].checkboxData" :key="item" :label="item.value">
                      <el-space>
                        <span>{{ item.name }}</span>
                        <el-input v-model="form['dataSourceId' + item.value]" placeholder="数据版本信息" style="width: 300px"
                          :disabled="!form.dataSource.includes(item.value)" readonly></el-input>
                        <el-button plain :disabled="!form.dataSource.includes(item.value)"
                          @click="chooseDataSource(item.value)">选择数据版本</el-button>
                      </el-space>
                    </el-checkbox>
                  </el-checkbox-group>
                </el-row>
                <!-- <el-row>
                  <el-button>选择易损性数据</el-button>
                </el-row> -->
              </el-col>
            </el-form-item>
          </el-row>
          <el-row class="border-bottom">
            <el-form-item label="地震输入方式" style="display:block;width: 100%;" prop="seismicInput">
              <el-col :span="24">
                <el-radio-group v-model="form.seismicInput" :disabled="!!form.id" @change="modeChange">
                  <el-radio v-for="item in inputMethods" :key="item.value" :label="item.value">
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
          </el-row>
          <el-row justify="end">
            <p :span="24">
              <el-button plain @click="saveAssessRecord">保存评估记录</el-button>
            </p>
          </el-row>
        </div>
        <div class="assess">
          <el-row>
            <el-form-item label="地震输入方式" style="display:block;width: 100%;">
              <el-col :span="24" v-if="form.seismicInput == 1">
                <span>烈度输入：</span>
                <el-select v-model="form.seismicInputValue" :disabled="!curId">
                  <el-option v-for="item in intensity" :key="item.dictItemId" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-col>
              <el-col :span="8" v-if="form.seismicInput == 2">
                <el-space>
                  <el-button plain @click="chooseInfluenceField" :disabled="!curId">选择影响场数据</el-button>
                  <el-input v-model="form.seismicInputValue" style="width: 300px;" :disabled="!curId"></el-input>
                </el-space>
              </el-col>
            </el-form-item>
          </el-row>
        </div>
        <el-row justify="end">
          <el-button plain @click="">网络拓扑图校验</el-button>
          <el-button plain @click="">破坏等级分析</el-button>
          <el-button plain @click="">功能失效分析</el-button>
        </el-row>
        <el-row>
          <el-col :span="24">
            <TableList :type="type" />
          </el-col>
        </el-row>

        <!-- <ConfirmTable :dataList="dataList" :url="url" :form="form" :loading="loading" v-if="TYPE.confirm == props.type" />
        <ProbabilityTable :dataList="dataList" :url="url" :form="form" :loading="loading"
          v-if="TYPE.probability == props.type" /> -->
      </el-space>
    </el-form>
  </el-dialog>
  <!-- 选择数据源 -->
  <DataSource v-model:open="dataSourceOpen" :selected="form['dataSourceId' + dataSourceType]"
    @getVersionCode="getVersionCode" :url="URL[type]" :type="dataSourceType" />
</template>
<script setup>
import { saveOrUpdateAssess, getById } from '@/api/lifelineProject/index'
import { getDict } from '@/api/system/dict.js'
import DataSource from '@/views/lifelineProject/components/dataSource.vue'
import { inputMethods, sourceData, URL, TYPE } from '@/views/lifelineProject/index'
import TableList from '@/views/lifelineProject/components/tableList.vue'

const props = defineProps({
  open: Boolean,
  url: String,
  type: String,
  dictDefault: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['update:open'])
const { proxy } = getCurrentInstance()
const initForm = () => ({
  dataSource: [],
  seismicInput: 1
})
const form = ref(initForm())
const dataSourceValid = (rule, value, cb) => {
  // if(!Array.isArray(value) && value.length == 1){
  //   value = [value]
  // }
  if (value.length == 0) {
    cb(new Error(`请选择${sourceData[props.type].name}!`))
  } else {
    value.map(item => {
      if (!form.value[rule.field + 'Id' + item]) {
        cb(new Error(`请选择${sourceData[props.type].name}!`))
      }
    })
    cb()
  }
}
const rules = {
  // code: [{ required: true, message: '请填写评估记录编号！', trigger: 'blur' }],
  name: [{ required: true, message: '请填写评估记录名称！', trigger: 'blur' }],
  info: [{ required: true, message: '请填写评估记录描述！', trigger: 'blur' }],
  dataSource: [
    { required: true, message: `请选择${sourceData[props.type].name}！`, trigger: 'change' },
    { validator: dataSourceValid, trigger: 'change' }
  ],
  seismicInput: [{ required: true, message: '请选择地震输入方式！', trigger: 'change' }],
}

const formLoading = ref(false)
// 字典项
const intensity = ref([])
const getDictData = (field, code) => {
  getDict(code).then(res => {
    intensity.value = res.data
    form.value[field] = res.data[0].dictItemCode
  })
}

const initOpen = () => {
  getDictData('seismicInputValue', 'ld')
}

// 查询详情
const curId = ref('')
proxy.$Bus.on('getDetail', (params) => {
  const { url, id } = params
  curId.value = id
  formLoading.value = true

  getById(url, { id }).then(res => {
    let data = res.data
    form.value = data
    form.value.dataSource = data.dataSource.split(',').map(item => Number(item))
    form.value.dataSource.map((item, index) => {
      form.value['dataSourceId' + item] = data.dataSourceId.split(',')[index]
    })
    formLoading.value = false
  })
})

proxy.$Bus.on('clearForm', () => {
  proxy.resetAllForm(form.value, initForm())
})

// 选择数据源
const dataSourceChange = val => {
  sourceData[props.type].checkboxData.map(item => {
    if (!val.includes(item.value)) {
      form.value['dataSourceId' + item.value] = ''
    }
  })
}
const dataSourceOpen = ref(false)
const dataSourceType = ref()
const chooseDataSource = (type) => {
  dataSourceOpen.value = true
  dataSourceType.value = type
}
const getVersionCode = val => {
  form.value['dataSourceId' + dataSourceType.value] = val
}

// 选择影响场数据
const influenceFieldOpen = ref(false)
const chooseInfluenceField = () => {
  influenceFieldOpen.value = true
}
const getInfluence = val => {
  form.value.condition = val
}
// 切换地震输入方式
const modeChange = (val) => {
  form.value.seismicInputValue = ''
  if (val == '0') {
    form.value.seismicInputValue = intensity.value[0].dictItemCode
  }
}

// 保存
const saveAssessRecord = () => {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      formLoading.value = true
      form.value.dataSourceId = form.value.dataSource.map(item => form.value['dataSourceId' + item]).join(',')
      form.value.dataSource = form.value.dataSource.join(',')
      saveOrUpdateAssess(props.url, { ...form.value, id: curId.value }).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('保存成功！')
          formLoading.value = false
          proxy.$Bus.emit('update-list')
          close()
        }
      })
    }
  })
}

// 关闭
const close = () => {
  emits('update:open', false)
  // dataList.value = []
  curId.value = ''
}

onBeforeUnmount(() => {
  proxy.$Bus.all.clear()
})
</script>

<style lang="scss" scoped>
.lifeLineAssess-dialog.el-dialog .el-dialog__header {
  background-color: transparent;
  height: auto;
}

.lifeLineAssess-dialog.el-dialog .el-dialog__body {
  padding: 0 20px 20px;
}

.el-form-item.el-form-item--default {
  margin: 10px 0;
}
:deep(.el-space) {
  width: 100%;

  &>.el-space__item {
    width: 100%;
  }
}

.assess {
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  .border-bottom {
    border-bottom: 1px solid var(--el-border-color-light);
    ;
  }

  .el-row {
    padding: 0 20px;
  }

  .title {
    font-weight: bold;
  }

  :deep(.column.el-radio-group) {
    flex-direction: column;
    align-items: start;

    &>.el-radio {
      &>.el-radio__label {
        &>.el-space {
          &>.el-space__item:first-of-type {
            margin-right: 50px !important;
          }
        }
      }
    }
  }

  .el-checkbox-group .el-checkbox {
    display: flex;
    margin: 10px 0;
  }
}
</style>